﻿using System;

namespace IOP.Protocols.MQTT.Package
{
    /// <summary>
    /// 连接确认包
    /// </summary>
    public struct ConnackPackage : IMQTTPackage
    {
        /// <summary>
        /// 控制报文类型
        /// </summary>
        public ControlPacketType PacketType { get => ControlPacketType.CONNACK; }

        /// <summary>
        /// 剩余长度
        /// </summary>
        public uint RemainingLength { get => 2; }

        /// <summary>
        /// 当前会话
        /// </summary>
        public bool SessionPresent;
        /// <summary>
        /// 返回码
        /// </summary>
        public ReturnCodeType ConnectReturnCode;

        /// <summary>
        /// 构造函数
        /// </summary>
        public ConnackPackage(bool sessionPresent, ReturnCodeType returnCode)
        {
            SessionPresent = sessionPresent;
            ConnectReturnCode = returnCode;
        }
        /// <summary>
        /// 转换为字节数组
        /// </summary>
        /// <returns></returns>
        public Span<byte> ToBytes()
        {
            Span<byte> bytes = stackalloc byte[4];
            Span<byte> result = new byte[4];
            var type = (byte)((byte)PacketType << 4);
            bytes[0] = type;
            bytes[1] = (byte)RemainingLength;
            bytes[2] = (byte)(SessionPresent ? 1 : 0);
            bytes[3] = (byte)ConnectReturnCode;
            bytes.CopyTo(result);
            return result;
        }
    }
}
